<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <el-form-item label="招聘岗位" prop="post">
        <el-cascader
          v-model="queryParams.post"
          :options="postOptions"
          :props="postCascaderProps"
          :show-all-levels="false"
          clearable
          filterable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="日期" prop="createTime">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="creator">
        <CascaderUser v-model="queryParams.creator" class="!w-240px" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
      </el-form-item>
    </el-form>


  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="flex flex-wrap gap-10px mb-10px">
      <el-button
        type="primary"
        plain
        @click="openBatchDialog"
        v-hasPermi="['hr:recruit-daily:create']"
      >
        <Icon icon="ep:plus" class="mr-5px"/>
        新增
      </el-button>
      <el-button
        type="success"
        plain
        @click="handleExport"
        :loading="exportLoading"
        v-hasPermi="['hr:recruit-daily:export']"
      >
        <Icon icon="ep:download" class="mr-5px"/>
        导出
      </el-button>

    </div>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
<!--      <el-table-column type="selection" width="55"/>-->
      <el-table-column label="创建热" align="center" prop="creatorName"/>
      <el-table-column label="招聘岗位" align="center" prop="post" width="200"/>
      <el-table-column label="沟通数量"  prop="communicationNum"/>
      <el-table-column label="回复数量" align="center" prop="replyNum"/>
      <!--      <el-table-column label="邀约数量" align="center" prop="inviteNum"/>-->
      <el-table-column label="硬性条件未转化数量" align="center" prop="prerequisiteUnconvertedNum"/>
      <el-table-column label="软性条件未转化数量" align="center"
                       prop="softConditionUnconvertedNum"/>
      <el-table-column label="通勤未转化数量" align="center" prop="commutingUnconvertedNum"/>
      <el-table-column label="公休未转化数量" align="center" prop="holidayUnconvertedNum"/>
      <el-table-column label="薪酬未转化数量" align="center" prop="remunerationUnconvertedNum"/>
      <el-table-column label="社保未转化数量" align="center" prop="socialSecurityUnconvertedNum"/>
      <el-table-column label="其他未转化数量" align="center" prop="otherSecurityUnconvertedNum"/>
      <!--      <el-table-column label="到面人数" align="center" prop="visitorsNum"/>-->
      <!--      <el-table-column label="合格人数" align="center" prop="qualifiedNum"/>-->
      <!--      <el-table-column label="到岗人数" align="center" prop="dutyNum"/>-->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
<!--      <el-table-column label="备注" align="center" prop="remark"/>-->
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['hr:recruit-daily:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['hr:recruit-daily:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <Dialog title="新增招聘日报"
          v-model="batchDialogVisible"
          append-to-body
          @closed="resetBatchDialog"

          width="1880"
  >
    <template #default>
      <el-card>
        <el-table :data="batchRows" row-key="rowId" size="small">
          <el-table-column label="序号" type="index" width="60"/>
          <el-table-column label="招聘岗位" min-width="140">
            <template #default="{row}">
              <el-cascader
                v-model="row.post"
                :options="postOptions"
                :props="postCascaderProps"
                :show-all-levels="false"
                filterable
                clearable
                size="small"

              />
            </template>
          </el-table-column>
          <el-table-column label="沟通数量" min-width="120">
            <template #default="{row}">
              <el-input-number v-model="row.communicationNum" :min="0" :controls="false"
                               size="small"/>
            </template>
          </el-table-column>
          <el-table-column label="回复数量" min-width="120">
            <template #default="{row}">
              <el-input-number v-model="row.replyNum" :min="0" :controls="false" size="small"/>
            </template>
          </el-table-column>
          <!--        <el-table-column label="邀约数量" min-width="120">-->
          <!--          <template #default="{row}">-->
          <!--            <el-input-number v-model="row.inviteNum" :min="0" :controls="false" size="small"/>-->
          <!--          </template>-->
          <!--        </el-table-column>-->
          <el-table-column label="硬性条件未转化数量" min-width="160">
            <template #default="{row}">
              <el-input-number v-model="row.prerequisiteUnconvertedNum" :min="0" :controls="false"
                               size="small"/>
            </template>
          </el-table-column>
          <el-table-column label="软性条件未转化数量" min-width="160">
            <template #default="{row}">
              <el-input-number v-model="row.softConditionUnconvertedNum" :min="0" :controls="false"
                               size="small"/>
            </template>
          </el-table-column>
          <el-table-column label="通勤未转化数量" min-width="140">
            <template #default="{row}">
              <el-input-number v-model="row.commutingUnconvertedNum" :min="0" :controls="false"
                               size="small"/>
            </template>
          </el-table-column>
          <el-table-column label="公休未转化数量" min-width="140">
            <template #default="{row}">
              <el-input-number v-model="row.holidayUnconvertedNum" :min="0" :controls="false"
                               size="small"/>
            </template>
          </el-table-column>
          <el-table-column label="薪酬未转化数量" min-width="140">
            <template #default="{row}">
              <el-input-number v-model="row.remunerationUnconvertedNum" :min="0" :controls="false"
                               size="small"/>
            </template>
          </el-table-column>
          <el-table-column label="社保未转化数量" min-width="140">
            <template #default="{row}">
              <el-input-number v-model="row.socialSecurityUnconvertedNum" :min="0" :controls="false"
                               size="small"/>
            </template>
          </el-table-column>
          <el-table-column label="其他未转化数量" min-width="140">
            <template #default="{row}">
              <el-input-number v-model="row.otherSecurityUnconvertedNum" :min="0" :controls="false"
                               size="small"/>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="90">
            <template #default="{row}">
              <el-button link type="danger" size="small" @click="removeBatchRow(row.rowId)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" plain class="!w-100% mt-10px" @click="addBatchRow">
          <Icon icon="ep:plus" class="mr-5px"/>
          新增行
        </el-button>
      </el-card>
    </template>
    <template #footer>
      <el-button @click="closeBatchDialog">取消</el-button>
      <el-button type="primary" @click="submitBatch" :loading="batchSubmitting">确定</el-button>
    </template>
  </Dialog>

  <!-- 表单弹窗：添加/修改 -->
  <RecruitDailyForm ref="formRef" @success="getList"/>
</template>

<script setup lang="ts">
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {RecruitDaily, RecruitDailyApi} from '@/api/business/hr/recruit/daily'
import {RecruitPost, RecruitPostApi} from '@/api/business/hr/recruit/post'
import {handleTree} from '@/utils/tree'
import CascaderUser from '@/components/CascaderUser/CascaderUser.vue'
import RecruitDailyForm from './RecruitDailyForm.vue'

interface RecruitDailyBatchRow {
  rowId: number
  post?: string
  communicationNum?: number
  replyNum?: number
  inviteNum?: number
  prerequisiteUnconvertedNum?: number
  softConditionUnconvertedNum?: number
  commutingUnconvertedNum?: number
  holidayUnconvertedNum?: number
  remunerationUnconvertedNum?: number
  socialSecurityUnconvertedNum?: number
  otherSecurityUnconvertedNum?: number
  visitorsNum?: number
  qualifiedNum?: number
  dutyNum?: number
  remark?: string
}

type RecruitDailyCreateRequest = Partial<Omit<RecruitDaily, 'id'>> & { post: string }

interface RecruitPostCascaderNode extends RecruitPost {
  isLeaf?: boolean
  children?: RecruitPostCascaderNode[]
}

/** 人力-招聘-日报 列表 */
defineOptions({name: 'HrRecruitDaily'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<RecruitDaily[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const showSearch = ref(true)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  post: undefined as string | undefined,
  creator: undefined as string | number | undefined
})
const dateRange = ref<string[]>([])
const postOptions = ref<RecruitPostCascaderNode[]>([])
const postCascaderProps = {
  checkStrictly: true,
  value: 'post',
  label: 'post',
  emitPath: false,
  leaf: 'isLeaf',
  multiple: false
}
const batchDialogVisible = ref(false)
const batchRows = ref<RecruitDailyBatchRow[]>([])
const batchSubmitting = ref(false)
let batchRowSeed = 1

const createEmptyBatchRow = (): RecruitDailyBatchRow => ({
  rowId: batchRowSeed++,
  post: undefined,
  communicationNum: undefined,
  replyNum: undefined,
  inviteNum: undefined,
  prerequisiteUnconvertedNum: undefined,
  softConditionUnconvertedNum: undefined,
  commutingUnconvertedNum: undefined,
  holidayUnconvertedNum: undefined,
  remunerationUnconvertedNum: undefined,
  socialSecurityUnconvertedNum: undefined,
  otherSecurityUnconvertedNum: undefined,
  visitorsNum: undefined,
  qualifiedNum: undefined,
  dutyNum: undefined,
  remark: undefined
})

const initBatchRows = () => {
  batchRowSeed = 1
  batchSubmitting.value = false
  batchRows.value = [createEmptyBatchRow()]
}

const openBatchDialog = async () => {
  if (!postOptions.value.length) {
    await loadPostOptions()
  }
  initBatchRows()
  batchDialogVisible.value = true
}

const closeBatchDialog = () => {
  batchDialogVisible.value = false
}

const resetBatchDialog = () => {
  batchSubmitting.value = false
  batchRowSeed = 1
  batchRows.value = []
}

const addBatchRow = () => {
  batchRows.value.push(createEmptyBatchRow())
}

const removeBatchRow = (rowId: number) => {
  if (batchRows.value.length === 1) {
    batchRows.value.splice(0, 1, createEmptyBatchRow())
    return
  }
  batchRows.value = batchRows.value.filter((item) => item.rowId !== rowId)
}

const normalizeNumber = (value?: number) => (value === undefined || value === null ? 0 : value)

const transformBatchRow = (row: RecruitDailyBatchRow): RecruitDailyCreateRequest => ({
  post: row.post!,
  communicationNum: normalizeNumber(row.communicationNum),
  replyNum: normalizeNumber(row.replyNum),
  inviteNum: normalizeNumber(row.inviteNum),
  prerequisiteUnconvertedNum: normalizeNumber(row.prerequisiteUnconvertedNum),
  softConditionUnconvertedNum: normalizeNumber(row.softConditionUnconvertedNum),
  commutingUnconvertedNum: normalizeNumber(row.commutingUnconvertedNum),
  holidayUnconvertedNum: normalizeNumber(row.holidayUnconvertedNum),
  remunerationUnconvertedNum: normalizeNumber(row.remunerationUnconvertedNum),
  socialSecurityUnconvertedNum: normalizeNumber(row.socialSecurityUnconvertedNum),
  otherSecurityUnconvertedNum: normalizeNumber(row.otherSecurityUnconvertedNum),
  visitorsNum: normalizeNumber(row.visitorsNum),
  qualifiedNum: normalizeNumber(row.qualifiedNum),
  dutyNum: normalizeNumber(row.dutyNum),
  remark: row.remark
})

const validateBatchRows = () => {
  if (!batchRows.value.length) {
    message.error('招聘日报不能为空')
    return false
  }
  for (let index = 0; index < batchRows.value.length; index++) {
    const row = batchRows.value[index]
    const displayIndex = index + 1
    if (!row.post) {
      message.error(`第${displayIndex}行错误：请填写招聘岗位`)
      return false
    }
    if (row.communicationNum === undefined) {
      message.error(`第${displayIndex}行错误：请填写沟通数量`)
      return false
    }
    if (row.replyNum === undefined) {
      message.error(`第${displayIndex}行错误：请填写回复数量`)
      return false
    }
  }
  return true
}

const submitBatch = async () => {
  if (!validateBatchRows()) {
    return
  }
  batchSubmitting.value = true
  try {
    const payloads = batchRows.value.map(row => transformBatchRow(row))
    await RecruitDailyApi.createRecruitDailyBatch(payloads as unknown as RecruitDaily[])
    message.success(t('common.createSuccess'))
    closeBatchDialog()
    await getList()
  } finally {
    batchSubmitting.value = false
  }
}
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams,
      createTime: dateRange.value.length === 2 ? [...dateRange.value] : undefined
    }
    if (!params.createTime) {
      delete params.createTime
    }
    const data = await RecruitDailyApi.getRecruitDailyPage(params)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const loadPostOptions = async () => {
  try {
    const data = await RecruitPostApi.getRecruitPostList({})
    const tree = handleTree(data || [], 'id', 'parentId') as RecruitPostCascaderNode[]
    const markLeaf = (nodes: RecruitPostCascaderNode[]) => {
      nodes.forEach((node) => {
        if (node.children && node.children.length > 0) {
          markLeaf(node.children as RecruitPostCascaderNode[])
          node.isLeaf = false
        } else {
          node.isLeaf = true
        }
      })
      return nodes
    }
    postOptions.value = markLeaf(tree)
  } catch {
    message.error('招聘岗位数据加载失败')
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = []
  queryParams.post = undefined
  queryParams.creator = undefined
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RecruitDailyApi.deleteRecruitDaily(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 批量删除人力-招聘-日报 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await RecruitDailyApi.deleteRecruitDailyList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {
  }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: RecruitDaily[]) => {
  checkedIds.value = records.map((item) => item.id!);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const params = {
      ...queryParams,
      createTime: dateRange.value.length === 2 ? [...dateRange.value] : undefined
    }
    if (!params.createTime) {
      delete params.createTime
    }
    const data = await RecruitDailyApi.exportRecruitDaily(params)
    download.excel(data, '人力-招聘-日报.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  loadPostOptions()
})
</script>
